﻿using AutoMapper;
using B.S.BasicData.Api.Read.Application.Command.Equipment;
using B.S.BasicData.Api.Read.Dtos;
using B.S.BasicData.Domain.Entities;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interfaces;
using MediatR;
using System.Transactions;

namespace B.S.BasicData.Api.Read.Application.CommandHandler.Equipment
{
    public class QueryEquipmentHandler : IRequestHandler<QueryEquipmentComand, ApiPaging<EquipmentDTO>>
    {
        private readonly IBaseRepository<EquipmentModel> accRepo;
        private readonly IMapper mapper;
        private readonly ILogger<QueryEquipmentHandler> logger;



        public QueryEquipmentHandler(IBaseRepository<EquipmentModel> accRepo, IMapper mapper, ILogger<QueryEquipmentHandler> logger)
        {
            this.accRepo = accRepo;
            this.mapper = mapper;
            this.logger = logger;
        }

        public Task<ApiPaging<EquipmentDTO>> Handle(QueryEquipmentComand request, CancellationToken cancellationToken)
        {
            //添加事务
            using (TransactionScope tran = new TransactionScope())

            {
                ApiPaging<EquipmentDTO> result = new ApiPaging<EquipmentDTO>();
                try
                {


                    var accounts = accRepo.Query().Result.Where(x => x.IsDeleted == false);



                    if (!string.IsNullOrEmpty(request.EquipmentCode))
                    {
                        accounts = accounts.Where(x => x.EquipmentCode == request.EquipmentCode);
                    }
                    if (!string.IsNullOrEmpty(request.EquipmentName))
                    {
                        accounts = accounts.Where(x => x.EquipmentName.Contains(request.EquipmentName));
                    }
                    
                    var linq = from a in accounts


                               select new EquipmentDTO
                               {
                                   Id = a.Id,
                                   EquipmentCode = a.EquipmentCode,
                                   EquipmentName = a.EquipmentName,
                                   Status = a.Status,
                                  
                               };
                    result.TotalCount = linq.Count();//总条数
                    result.TotalPage = (int)Math.Ceiling(result.TotalCount * 1.0 / request.PageSize);//总页数

                    var models = linq.OrderBy(x => x.Id).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();


                    result.Items = mapper.Map<List<EquipmentDTO>>(models);
                    result.Code = ApiEnums.Success;
                    result.Msg = "分页数据查询成功!";




                    return Task.FromResult(result);



                }
                catch (Exception e)
                {


                    logger.LogError("查询失败=>" + e.Message);

                    throw;
                }


            }
        }
    }
}

